#include "usermanagementwidget.h"
#include <QApplication>
#include <QMenu>
#include <QDateTime>
#include <QInputDialog>
#include <QRegularExpression>

UserManagementWidget::UserManagementWidget(QWidget *parent)
    : QWidget(parent)
    , m_userManager(nullptr)
    , m_mainLayout(nullptr)
    , m_searchLabel(nullptr)
    , m_searchEdit(nullptr)
    , m_refreshButton(nullptr)
    , m_userTable(nullptr)
    , m_buttonLayout(nullptr)
    , m_buttonWidget(nullptr)
    , m_refreshDataButton(nullptr)
    , m_exportDataButton(nullptr)
    , m_statusLabel(nullptr)
    , m_searchTimer(nullptr)
{
    setupUI();
    setupConnections();
    applyStyles();
    
    // 初始化搜索定时器
    m_searchTimer = new QTimer(this);
    m_searchTimer->setSingleShot(true);
    m_searchTimer->setInterval(300); // 300ms防抖
    connect(m_searchTimer, &QTimer::timeout, this, &UserManagementWidget::filterUserData);
}

UserManagementWidget::~UserManagementWidget()
{
    // Qt会自动清理子对象
}

void UserManagementWidget::setUserManager(UserManager *manager)
{
    if (m_userManager) {
        // 断开原有连接
        disconnect(m_userManager, nullptr, this, nullptr);
    }
    
    m_userManager = manager;
    
    if (m_userManager) {
        // 连接信号
        connect(m_userManager, &UserManager::userRegistered,
                this, &UserManagementWidget::onUserRegistered);
        
        // 延迟连接DataManager的外部文件变更信号，避免初始化冲突
        QTimer::singleShot(100, this, [this]() {
            connect(&DataManager::instance(), &DataManager::externalFileChanged,
                    this, &UserManagementWidget::onExternalFileChanged);
        });
        
        // 延迟加载数据，避免在信号连接过程中引起死锁
        QTimer::singleShot(0, this, &UserManagementWidget::refreshData);
    }
}

void UserManagementWidget::refreshData()
{
    if (!m_userManager) {
        showStatusMessage("用户管理器未初始化", true);
        return;
    }
    
    loadUserData();
    filterUserData();
    showStatusMessage("数据已刷新");
}

void UserManagementWidget::setupUI()
{
    // 主布局 - 改为垂直布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(5, 5, 5, 5);
    m_mainLayout->setSpacing(8);
    
    // 搜索区域
    QHBoxLayout *searchLayout = new QHBoxLayout();
    searchLayout->setSpacing(5);
    
    m_searchLabel = new QLabel("搜索用户:", this);
    m_searchLabel->setMinimumWidth(60);
    m_searchEdit = new QLineEdit(this);
    m_searchEdit->setPlaceholderText("用户名...");
    
    m_refreshButton = new QPushButton("刷新", this);
    m_refreshButton->setMaximumWidth(60);
    
    searchLayout->addWidget(m_searchLabel);
    searchLayout->addWidget(m_searchEdit, 1);
    searchLayout->addWidget(m_refreshButton);
    searchLayout->addStretch();
    
    m_mainLayout->addLayout(searchLayout);
    
    // 创建用户表格
    setupUserTable();
    m_mainLayout->addWidget(m_userTable);
    
    // 操作按钮区域
    m_buttonWidget = new QWidget();
    m_buttonLayout = new QHBoxLayout(m_buttonWidget);
    m_buttonLayout->setContentsMargins(0, 0, 0, 0);
    
    m_refreshDataButton = new QPushButton("刷新数据", this);
    m_exportDataButton = new QPushButton("导出数据", this);
    
    m_buttonLayout->addWidget(m_refreshDataButton);
    m_buttonLayout->addWidget(m_exportDataButton);
    m_buttonLayout->addStretch();
    
    m_mainLayout->addWidget(m_buttonWidget);
    
    // 状态显示
    m_statusLabel = new QPushButton("就绪 - 双击用户行查看详细信息", this);
    m_statusLabel->setObjectName("statusLabel");
    m_statusLabel->setEnabled(false);
    m_statusLabel->setFixedHeight(35);
    m_statusLabel->setStyleSheet(
        "QPushButton { "
        "background-color: #f8f9fa; "
        "color: #2c3e50; "
        "border: 2px solid #e9ecef; "
        "border-radius: 4px; "
        "padding: 6px 12px; "
        "font-size: 12px; "
        "font-weight: 500; "
        "text-align: center; "
        "}"
        "QPushButton:disabled { "
        "background-color: #f8f9fa; "
        "color: #2c3e50; "
        "border: 2px solid #e9ecef; "
        "}"
    );
    
    m_mainLayout->addWidget(m_statusLabel);
}

void UserManagementWidget::setupUserTable()
{
    m_userTable = new QTableWidget(this);
    m_userTable->setColumnCount(COL_COUNT);
    
    // 设置表头 - 移除邮箱列
    QStringList headers = {"ID", "用户名", "注册时间", "最后登录", "状态"};
    m_userTable->setHorizontalHeaderLabels(headers);
    
    // 表格设置 - 针对1024*600优化
    m_userTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_userTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_userTable->setAlternatingRowColors(true);
    m_userTable->setSortingEnabled(true);
    m_userTable->setContextMenuPolicy(Qt::CustomContextMenu);
    
    // 设置表格为只读模式
    m_userTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    
    // 优化表格行高和字体
    m_userTable->verticalHeader()->setDefaultSectionSize(28);
    m_userTable->verticalHeader()->hide();
    QFont tableFont = m_userTable->font();
    tableFont.setPointSize(9);
    m_userTable->setFont(tableFont);
    
    // 列宽设置 - 移除邮箱列后优化
    QHeaderView *header = m_userTable->horizontalHeader();
    header->setSectionResizeMode(COL_ID, QHeaderView::Fixed);
    header->setSectionResizeMode(COL_USERNAME, QHeaderView::Stretch);
    header->setSectionResizeMode(COL_REG_DATE, QHeaderView::Fixed);
    header->setSectionResizeMode(COL_LAST_LOGIN, QHeaderView::Fixed);
    header->setSectionResizeMode(COL_STATUS, QHeaderView::Fixed);
    
    // 设置固定列宽 - 优化ID列和其他列宽度
    m_userTable->setColumnWidth(COL_ID, 80);
    m_userTable->setColumnWidth(COL_REG_DATE, 110);
    m_userTable->setColumnWidth(COL_LAST_LOGIN, 110);
    m_userTable->setColumnWidth(COL_STATUS, 80);
    
    // 隐藏ID列
    m_userTable->setColumnHidden(COL_ID, true);
}



void UserManagementWidget::setupConnections()
{
    // 搜索
    connect(m_searchEdit, &QLineEdit::textChanged, this, [this]() {
        m_searchTimer->stop();
        m_searchTimer->start();
    });
    connect(m_refreshButton, &QPushButton::clicked,
            this, &UserManagementWidget::onRefreshClicked);
    
    // 表格操作 - 双击查看详情
    connect(m_userTable, &QTableWidget::cellDoubleClicked,
            this, &UserManagementWidget::onTableItemDoubleClicked);
    connect(m_userTable, &QTableWidget::customContextMenuRequested,
            this, &UserManagementWidget::onTableContextMenuRequested);
    
    // 操作按钮
    connect(m_refreshDataButton, &QPushButton::clicked,
            this, &UserManagementWidget::onRefreshDataClicked);
    connect(m_exportDataButton, &QPushButton::clicked,
            this, &UserManagementWidget::onExportDataClicked);
}

void UserManagementWidget::applyStyles()
{
    setStyleSheet(R"(
        UserManagementWidget {
            background-color: #f8f9fa;
            font-size: 12px;
        }
        
        QTableWidget {
            gridline-color: #e0e0e0;
            background-color: white;
            selection-background-color: #3498db;
            selection-color: white;
            border: 1px solid #bdc3c7;
            border-radius: 3px;
            font-size: 11px;
        }
        
        QTableWidget::item {
            padding: 4px 6px;
            border-bottom: 1px solid #ecf0f1;
            height: 24px;
        }
        
        QTableWidget::item:selected {
            background-color: #3498db;
            color: white;
        }
        
        QTableWidget QHeaderView::section {
            background-color: #34495e;
            color: white;
            padding: 5px;
            border: none;
            font-weight: bold;
            font-size: 11px;
            height: 26px;
        }
        
        #infoTitle {
            font-size: 14px;
            font-weight: bold;
            color: #2c3e50;
            padding: 6px;
            background-color: #ecf0f1;
            border-radius: 3px;
        }
        
        QGroupBox {
            font-weight: bold;
            color: #2c3e50;
            border: 2px solid #bdc3c7;
            border-radius: 5px;
            margin-top: 10px;
            padding-top: 10px;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 10px;
            padding: 0 5px 0 5px;
        }
        
        QLineEdit {
            border: 1px solid #bdc3c7;
            border-radius: 3px;
            padding: 3px 6px;
            background-color: white;
            font-size: 11px;
            min-height: 20px;
        }
        
        QLineEdit:focus {
            border-color: #3498db;
        }
        
        QPushButton {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 3px;
            font-weight: bold;
            font-size: 11px;
            min-height: 24px;
        }
        
        QPushButton:hover {
            background-color: #2980b9;
        }
        
        QPushButton:pressed {
            background-color: #21618c;
        }
        
        QPushButton:disabled {
            background-color: #bdc3c7;
            color: #7f8c8d;
        }
        
        QPushButton[objectName="resetPasswordButton"] {
            background-color: #e74c3c;
        }
        
        QPushButton[objectName="resetPasswordButton"]:hover {
            background-color: #c0392b;
        }
    )");
    
    // 设置按钮对象名用于样式
    // 按钮样式在各自创建时设置
}

void UserManagementWidget::loadUserData()
{
    if (!m_userManager) return;
    
    if (!m_userManager->isAdmin()) {
        if (!m_allUsers.isEmpty()) {
            m_allUsers.clear();
        }
        return;
    }
    
    m_allUsers = m_userManager->getAllCustomers();
    
    // 更新统计信息
    int totalUsers = m_allUsers.size();
    int activeUsers = 0;
    int newUsers = 0;
    
    QDateTime now = QDateTime::currentDateTime();
    QDateTime weekAgo = now.addDays(-7);
    
    for (const Customer &user : m_allUsers) {
        // 检查活跃用户 (最近7天有登录)
        if (user.lastLoginDate.isValid() && user.lastLoginDate >= weekAgo) {
            activeUsers++;
        }
        
        // 检查新用户 (最近7天注册)
        if (user.registrationDate.isValid() && user.registrationDate >= weekAgo) {
            newUsers++;
        }
    }
    
    // 统计信息在状态栏显示
    Q_UNUSED(activeUsers);
    Q_UNUSED(newUsers);
    
    showStatusMessage(QString("已加载 %1 个用户").arg(totalUsers));
}

void UserManagementWidget::updateUserTable()
{
    m_userTable->setSortingEnabled(false);
    m_userTable->setRowCount(m_filteredUsers.size());
    
    for (int row = 0; row < m_filteredUsers.size(); ++row) {
        const Customer &user = m_filteredUsers.at(row);
        
        // ID (隐藏列)
        m_userTable->setItem(row, COL_ID, new QTableWidgetItem(user.id));
        
        // 用户名
        m_userTable->setItem(row, COL_USERNAME, new QTableWidgetItem(user.username));
        
        // 注册时间
        QString regDate = user.registrationDate.isValid() ? 
            user.registrationDate.toString("yyyy-MM-dd") : "未知";
        m_userTable->setItem(row, COL_REG_DATE, new QTableWidgetItem(regDate));
        
        // 最后登录
        QString lastLogin = user.lastLoginDate.isValid() ? 
            user.lastLoginDate.toString("yyyy-MM-dd") : "从未";
        m_userTable->setItem(row, COL_LAST_LOGIN, new QTableWidgetItem(lastLogin));
        
        // 状态
        QString status = "正常";
        QTableWidgetItem *statusItem = new QTableWidgetItem(status);
        statusItem->setTextAlignment(Qt::AlignCenter);
        m_userTable->setItem(row, COL_STATUS, statusItem);
    }
    
    m_userTable->setSortingEnabled(true);
    
    // 更新状态
    showStatusMessage(QString("显示 %1 个用户").arg(m_filteredUsers.size()));
}

void UserManagementWidget::filterUserData()
{
    QString searchText = m_searchEdit->text().trimmed();
    
    m_filteredUsers.clear();
    
    for (const Customer &user : m_allUsers) {
        bool matches = true;
        
        // 搜索过滤
        if (!searchText.isEmpty()) {
            if (!user.username.contains(searchText, Qt::CaseInsensitive) &&
                !user.email.contains(searchText, Qt::CaseInsensitive)) {
                matches = false;
            }
        }
        
        if (matches) {
            m_filteredUsers.append(user);
        }
    }
    
    updateUserTable();
}



// ============================================================================
// 槽函数实现
// ============================================================================



void UserManagementWidget::onSearchTextChanged()
{
    // 由定时器处理，防抖动
}

void UserManagementWidget::onRefreshClicked()
{
    refreshData();
}





void UserManagementWidget::onTableItemDoubleClicked(int row, int column)
{
    Q_UNUSED(column);
    
    if (row >= 0 && row < m_filteredUsers.size()) {
        Customer user = getUserByRow(row);
        if (!user.id.isEmpty()) {
            showUserDetailDialog(user);
        }
    }
}

void UserManagementWidget::onTableContextMenuRequested(const QPoint &pos)
{
    QTableWidgetItem *item = m_userTable->itemAt(pos);
    if (!item) return;
    
    int row = item->row();
    if (row < 0 || row >= m_filteredUsers.size()) return;
    
    Customer user = getUserByRow(row);
    if (user.id.isEmpty()) return;
    
    QMenu contextMenu(this);
    
    QAction *viewAction = contextMenu.addAction("查看详情");
    QAction *resetAction = contextMenu.addAction("重置密码");
    
    QAction *action = contextMenu.exec(m_userTable->mapToGlobal(pos));
    if (action == viewAction) {
        showUserDetailDialog(user);
    } else if (action == resetAction) {
        if (resetUserPassword(user.id)) {
            showStatusMessage("密码重置成功");
        } else {
            showStatusMessage("密码重置失败", true);
        }
    }
}

// ============================================================================
// 信号响应实现
// ============================================================================

void UserManagementWidget::onUserRegistered(const Customer &user)
{
    Q_UNUSED(user);
    // 用户注册时刷新数据
    refreshData();
}

void UserManagementWidget::onUserUpdated(const Customer &user)
{
    Q_UNUSED(user);
    // 用户信息更新时刷新数据
    refreshData();
}

void UserManagementWidget::onUserPasswordChanged(const QString &userId)
{
    Q_UNUSED(userId);
    showStatusMessage("用户密码已更新");
}

void UserManagementWidget::onExternalFileChanged(DataType dataType, const QString& filePath)
{
    Q_UNUSED(filePath);
    
    if (dataType == DataType::USERS) {
        // 用户数据文件变更时延迟刷新，避免在信号处理中获取锁导致死锁
        QTimer::singleShot(100, this, [this]() {
            refreshData();
        });
    }
}

// ============================================================================
// 辅助方法实现
// ============================================================================



bool UserManagementWidget::resetUserPassword(const QString &userId)
{
    if (!m_userManager) return false;
    
    return m_userManager->resetCustomerPassword(userId);
}

void UserManagementWidget::showStatusMessage(const QString &message, bool isError)
{
    if (!m_statusLabel) return;
    
    m_statusLabel->setText(message);
    
    // 根据消息类型设置样式
    QString style = isError ? 
        "QPushButton { background-color: #ffebee; color: #d32f2f; border: 2px solid #f44336; }" :
        "QPushButton { background-color: #e8f5e8; color: #2e7d32; border: 2px solid #4caf50; }";
    
    m_statusLabel->setStyleSheet(style + 
        "QPushButton { border-radius: 4px; padding: 6px 12px; font-size: 12px; font-weight: 500; }");
    
    // 发送状态消息信号
    emit statusMessageChanged(message);
    
    // 3秒后恢复默认样式
    QTimer::singleShot(3000, this, [this]() {
        if (m_statusLabel) {
            m_statusLabel->setText("就绪");
            m_statusLabel->setStyleSheet(
                "QPushButton { "
                "background-color: #f8f9fa; "
                "color: #2c3e50; "
                "border: 2px solid #e9ecef; "
                "border-radius: 4px; "
                "padding: 6px 12px; "
                "font-size: 12px; "
                "font-weight: 500; "
                "text-align: center; "
                "}"
            );
        }
    });
}

QString UserManagementWidget::getMessageBoxStyleSheet() const
{
    return R"(
        QMessageBox {
            background-color: #f5f5f5;
            border: 2px solid #bdc3c7;
            border-radius: 8px;
            font-family: "DejaVu Sans", "SimSun", "Microsoft YaHei";
            font-size: 12px;
        }
        
        QMessageBox QLabel {
            color: #2c3e50;
            font-size: 13px;
            margin: 10px;
            background-color: transparent;
        }
        
        QMessageBox QPushButton {
            background-color: #3498db;
            color: #ffffff;
            border: none;
            border-radius: 4px;
            padding: 8px 20px;
            min-width: 80px;
            font-weight: bold;
            font-size: 12px;
        }
        
        QMessageBox QPushButton:hover {
            background-color: #2980b9;
        }
        
        QMessageBox QPushButton:pressed {
            background-color: #21618c;
        }
        
        QMessageBox QPushButton:focus {
            outline: none;
            border: 2px solid #5dade2;
        }
    )";
}

// ============================================================================
// 新增槽函数实现
// ============================================================================

void UserManagementWidget::onRefreshDataClicked()
{
    loadUserData();
    showStatusMessage("数据已刷新");
}

void UserManagementWidget::onExportDataClicked()
{
    showStatusMessage("导出功能待实现");
}

Customer UserManagementWidget::getUserByRow(int row)
{
    if (row >= 0 && row < m_filteredUsers.size()) {
        return m_filteredUsers.at(row);
    }
    return Customer();
}

void UserManagementWidget::showUserDetailDialog(const Customer &user)
{
    if (user.id.isEmpty()) {
        showStatusMessage("用户信息无效", true);
        return;
    }

    // 创建用户详细信息对话框
    QDialog *dialog = new QDialog(this);
    dialog->setWindowTitle("用户详细信息");
    dialog->setWindowIcon(this->windowIcon());
    dialog->setModal(true);
    dialog->resize(400, 500);
    
    QVBoxLayout *layout = new QVBoxLayout(dialog);
    layout->setSpacing(12);
    layout->setContentsMargins(20, 20, 20, 20);

    // 标题
    QLabel *titleLabel = new QLabel(QString("用户: %1").arg(user.username));
    titleLabel->setStyleSheet("font-size: 16px; font-weight: bold; color: #2c3e50;");
    layout->addWidget(titleLabel);

    // 分隔线
    QFrame *line = new QFrame();
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    layout->addWidget(line);

    // 用户信息
    QGroupBox *infoGroup = new QGroupBox("基本信息");
    QVBoxLayout *infoLayout = new QVBoxLayout(infoGroup);
    
    infoLayout->addWidget(new QLabel(QString("用户ID: %1").arg(user.id)));
    infoLayout->addWidget(new QLabel(QString("用户名: %1").arg(user.username)));
    infoLayout->addWidget(new QLabel(QString("邮箱: %1").arg(user.email.isEmpty() ? "未设置" : user.email)));
    
    QString regDate = user.registrationDate.isValid() ? 
        user.registrationDate.toString("yyyy-MM-dd hh:mm:ss") : "未知";
    infoLayout->addWidget(new QLabel(QString("注册时间: %1").arg(regDate)));
    
    QString lastLogin = user.lastLoginDate.isValid() ? 
        user.lastLoginDate.toString("yyyy-MM-dd hh:mm:ss") : "从未登录";
    infoLayout->addWidget(new QLabel(QString("最后登录: %1").arg(lastLogin)));
    
    layout->addWidget(infoGroup);

    // 密码信息组
    QGroupBox *passwordGroup = new QGroupBox("密码信息");
    QVBoxLayout *passwordLayout = new QVBoxLayout(passwordGroup);
    
    // 显示实际密码
    QString actualPassword = user.plainPassword.isEmpty() ? "暂无明文密码记录" : user.plainPassword;
    QLabel *passwordLabel = new QLabel(QString("当前密码: %1").arg(actualPassword));
    passwordLabel->setWordWrap(true);
    passwordLabel->setStyleSheet("font-family: monospace; font-size: 12px; background-color: #f8f9fa; padding: 8px; border: 1px solid #dee2e6; border-radius: 4px; color: #e74c3c; font-weight: bold;");
    passwordLayout->addWidget(passwordLabel);
    
    // 重置密码按钮
    QPushButton *resetPasswordBtn = new QPushButton("重置密码为 abc123456");
    resetPasswordBtn->setStyleSheet("QPushButton { background-color: #f39c12; color: white; border: none; padding: 8px 16px; border-radius: 4px; font-weight: bold; } QPushButton:hover { background-color: #e67e22; }");
    connect(resetPasswordBtn, &QPushButton::clicked, [this, user]() {
        if (resetUserPassword(user.id)) {
            QMessageBox::information(this, "成功", "密码已重置为: abc123456");
        }
    });
    passwordLayout->addWidget(resetPasswordBtn);
    
    layout->addWidget(passwordGroup);

    // 按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *closeBtn = new QPushButton("关闭");
    closeBtn->setStyleSheet("QPushButton { background-color: #95a5a6; color: white; border: none; padding: 8px 20px; border-radius: 4px; } QPushButton:hover { background-color: #7f8c8d; }");
    connect(closeBtn, &QPushButton::clicked, dialog, &QDialog::accept);
    
    buttonLayout->addStretch();
    buttonLayout->addWidget(closeBtn);
    layout->addLayout(buttonLayout);

    // 设置对话框样式
    dialog->setStyleSheet(getMessageBoxStyleSheet());
    
    dialog->exec();
    dialog->deleteLater();
}
